#!D:\Python27\python.exe
# -*- coding: utf-8 -*-
'''
    Implements upload command

    :copyright: (c) 2014 by Duxin.
'''

import cgi
import os 
import Cookie

import command
import app
import sessions
from db.db_manager import UserDAO

#Max file size allowed for uploading.
MAX_FILE_SIZE = 1000000

class Upload(object): 
    '''
        Upload Command is not a derived class. This is because Upload uses different Content-type.
        If user has logged, receives the file uploaded and stores it into database.
        
        Noted: Currently, Since we don't find a way to write binary data into database in a streamer
        way, file is uploaded into memory buffer firstly and then is writen into database. So there is a 
        potential problem when a large number of upload request are processing.
    '''
    
    def execute(self):
        try: # Windows needs stdio set for binary mode.  
            import msvcrt  
            msvcrt.setmode (0, os.O_BINARY) # stdin  = 0  
            msvcrt.setmode (1, os.O_BINARY) # stdout = 1  
        except ImportError as e:  
            return "error"
            
        # A nested FieldStorage instance holds the file  
        self.form = cgi.FieldStorage()
        fileitem = self.form['file']  
        
        # Test if the file was uploaded  
        if fileitem.file:  
            chunk = fileitem.file.read(MAX_FILE_SIZE)  
            
            cookie = Cookie.SimpleCookie()
            string_cookie = os.environ.get('HTTP_COOKIE')
            
            session = None
            
            # If already existent session
            if string_cookie:
                cookie.load(string_cookie)
                sid = cookie['sid'].value
                session = sessions.Session.get_session(sid)
            else:
                print "Status: 403 Forbidden\n\n"
                return ""
            
            self.session = session
        
            user = session.get_attribute('user')
            
            user.avatars[0] = chunk
            db = UserDAO.persist(user)
            
            return True
        else:  
            return False
    
upload = Upload()
if upload.execute():
    print "Location: ../index.html\n\n"
else:
    print "Content-type: text/html\n\n上传失败"
